package xh;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;

/**
 * Created by Administrator on 2016/7/6.
 */
public class RemoteFileListReceiver {

    FileListManager fileListManager;

    private byte[] buffer = new byte[Global.FileListUdpBufferMax];

    public RemoteFileListReceiver(FileListManager fileListManager) {
        this.fileListManager = fileListManager;
    }

    public void start() {

        new Thread(new Runnable() {
            public void run() {

                try {
                    DatagramSocket dataSocket = new DatagramSocket(Global.FileListUdpPort);
                    DatagramPacket dataPacket = new DatagramPacket(buffer, buffer.length);

                    while (true) {
                        dataSocket.receive(dataPacket);
                        int recvLength = dataPacket.getLength();

                        String remoteIp = dataPacket.getAddress().getHostAddress();
                        String ctt = new String(buffer, 0, recvLength);


                        System.out.println(remoteIp + " send:" + ctt);
                        String[] fileIds = ctt.split("###");

                        if (fileIds != null && fileIds.length != 0) {
                            fileListManager.receiveFileIds(Arrays.asList(fileIds), remoteIp);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
